<?php

namespace app\api\controller;

use app\api\controller\MobileSeller;
use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class SellerBooth extends MobileSeller
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/sellerpromotionbooth.lang.php');

        if (intval(config('promotion_allow')) !== 1) {
        	ds_json_encode(10001,lang('promotion_unavailable'));
        }
    }

    /**
     * 套餐商品列表
     */
    public function index()
    {
        $pbooth_model = model('pbooth');
        // 更新套餐状态
        $where = array();
        $where['store_id'] = $this->seller_info['store_id'];
        $where['boothquota_endtime'] = array('lt', TIMESTAMP);
        $pbooth_model->editBoothClose($where);

        $isPlatformStore = check_platform_store() ? true : false;
        $data['isPlatformStore']=$isPlatformStore;
        $hasList = $isPlatformStore;
	    $data['goods_list']=[];
	    $data['goodsclass_list']=[];
	    $data['booth_quota']=[];
        if (!$isPlatformStore) {
            // 检查是否已购买套餐
            $where = array();
            $where['store_id'] = $this->seller_info['store_id'];
            $booth_quota = $pbooth_model->getBoothquotaInfo($where);
            $data['booth_quota']=$booth_quota;
            if (!empty($booth_quota)) {
                $hasList = true;
            }elseif(intval(config('promotion_booth_price'))==0){
                $hasList = true;
            }else{
                $update = array('boothgoods_state' => $pbooth_model::STATE0);
                $pbooth_model->editBooth($update, $where);
            }
        }

        if ($hasList) {
            // 查询已选择商品
            $boothgoods_list = $pbooth_model->getBoothgoodsList(array('store_id' => $this->seller_info['store_id']), 'goods_id');
            if (!empty($boothgoods_list)) {
                $goodsid_array = array();
                foreach ($boothgoods_list as $val) {
                    $goodsid_array[] = $val['goods_id'];
                }
                $goods_list = model('goods')->getGoodsList(array('goods_id' => array('in', $goodsid_array)), 'goods_id,goods_name,goods_image,goods_price,store_id,gc_id');
                if (!empty($goods_list)) {
                    $gcid_array = array();  // 商品分类id
                    foreach ($goods_list as $key => $val) {
                        $gcid_array[] = $val['gc_id'];
                        $goods_list[$key]['goods_image'] = goods_thumb($val);
                        $goods_list[$key]['url'] = url('Goods/index', array('goods_id' => $val['goods_id']));
                    }
                    $goodsclass_list = model('goodsclass')->getGoodsclassListByIds($gcid_array);
                    $goodsclass_list = array_under_reset($goodsclass_list, 'gc_id');
                    $data['goods_list']=$goods_list;
                    $data['goodsclass_list']=$goodsclass_list;

                }
            }
        }
        ds_json_encode(10000,"查询成功",$data);
    }

    /**
     * 选择商品
     */
    public function booth_select_goods()
    {
        $goods_model = model('goods');
        $condition = array();
        $condition['store_id'] = $this->seller_info['store_id'];
        $goods_name = input('post.goods_name');
        if ($goods_name != '') {
            $condition['goods_name'] = array('like', '%' . $goods_name . '%');
        }
        $goods_list = $goods_model->getGoodsOnlineList($condition, '*', 10);
	    $data['goods_list']=$goods_list;
	    $data['show_page']=$goods_model->page_info->render();
	    ds_json_encode(10000,"查询成功",$data);
    }

    /**
     * 购买套餐
     */
    public function booth_quota_add()
    {
        if (request()->isPost()) {
            if(intval(config('promotion_booth_price'))==0){
                ds_json_encode(10001,lang('param_error'));
            }
            $quantity = intval(input('post.booth_quota_quantity')); // 购买的数量（月）
            $price_quantity = $quantity * intval(config('promotion_booth_price')); // 扣款数
            if ($quantity <= 0 || $quantity > 12) {
                ds_json_encode(10001,lang('param_error'));
            }
            // 实例化模型
            $pbooth_model = model('pbooth');

            $data = array();
            $data['store_id'] = $this->seller_info['store_id'];
            $data['store_name'] = session('store_name');
            $data['boothquota_starttime'] = TIMESTAMP;
            $data['boothquota_endtime'] = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
            $data['boothquota_state'] = 1;

            $return = $pbooth_model->addBoothquota($data);
            if ($return) {
                // 添加店铺费用记录
                $this->recordStorecost($price_quantity, '购买推荐展位');

                // 添加任务队列
                $end_time = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
                $this->addcron(array('exetime' => $end_time, 'exeid' => $this->seller_info['store_id'], 'type' => 4), true);
                $this->recordSellerlog('购买' . $quantity . '套推荐展位，单位元');
                ds_json_encode(10000,lang('ds_common_op_succ'));
            }
            else {
                ds_json_encode(10001,lang('ds_common_op_fail'));
            }
        }
        ds_json_encode(10001,"提交方式错误");
    }

    /**
     * 套餐续费
     */
    public function booth_renew()
    {
        if (request()->isPost()) {
            if(intval(config('promotion_booth_price'))==0){
                ds_json_encode(10001,lang('param_error'));
            }
            $pbooth_model = model('pbooth');
            $quantity = intval(input('post.booth_quota_quantity')); // 购买数量（月）
            $price_quantity = $quantity * intval(config('promotion_booth_price')); // 扣款数
            if ($quantity <= 0 || $quantity > 12) {
                ds_json_encode(10001,lang('param_error'));
            }
            $where = array();
            $where['store_id'] = $this->seller_info['store_id'];
            $booth_quota = $pbooth_model->getBoothquotaInfo($where);
            if ($booth_quota['boothquota_endtime'] > TIMESTAMP) {
                // 套餐未超时(结束时间+购买时间)
                $update['boothquota_endtime'] = intval($booth_quota['boothquota_endtime']) + 60 * 60 * 24 * 30 * $quantity;
            }
            else {
                // 套餐已超时(当前时间+购买时间)
                $update['boothquota_endtime'] = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
            }
            $return = $pbooth_model->editBoothquotaOpen($update, $where);

            if ($return) {
                // 添加店铺费用记录
                $this->recordStorecost($price_quantity, '购买推荐展位');

                // 添加任务队列
                $end_time = TIMESTAMP + 60 * 60 * 24 * 30 * $quantity;
                $this->addcron(array('exetime' => $end_time, 'exeid' => $this->seller_info['store_id'], 'type' => 4), true);
                $this->recordSellerlog('续费' . $quantity . '套推荐展位，单位元');
                ds_json_encode(10000,lang('ds_common_op_succ'));
            }
            else {
                ds_json_encode(10001,lang('ds_common_op_fail'));
            }
        }
	    ds_json_encode(10001,"提交方式错误");
    }

    /**
     * 选择商品
     */
    public function choosed_goods()
    {
        $gid = input('param.gid');
        if ($gid <= 0) {
            $data = array('result' => 'false', 'msg' => lang('param_error'));
            $this->_echoJson($data);
        }

        // 验证商品是否存在
        $goods_info = model('goods')->getGoodsInfoByID($gid);
        if (empty($goods_info) || $goods_info['store_id'] != $this->seller_info['store_id']) {
            $data = array('result' => 'false', 'msg' => lang('param_error'));
            $this->_echoJson($data);
        }

        $pbooth_model = model('pbooth');

        if (!check_platform_store()) {
            // 验证套餐时候过期
            $booth_info = $pbooth_model->getBoothquotaInfo(array(
             'store_id' => $this->seller_info['store_id'],
              'boothquota_endtime' => array('gt', TIMESTAMP)
              ), 'boothquota_id');
            if (empty($booth_info)) {
                if(intval(config('promotion_booth_price'))!=0){
                    $data = array('result' => 'false', 'msg' => lang('boothquota_expire'));
                    $this->_echoJson($data);
                }
            }
        }

        // 验证已添加商品数量，及选择商品是否已经被添加过
        $bootgoods_info = $pbooth_model->getBoothgoodsList(array('store_id' => $this->seller_info['store_id']), 'goods_id');
        // 已添加商品总数
        if (count($bootgoods_info) >= config('promotion_booth_goods_sum')) {
            $data = array('result' => 'false', 'msg' => sprintf(lang('promotion_booth_goods_sum_error'),config('promotion_booth_goods_sum')));
            $this->_echoJson($data);
        }
        // 商品是否已经被添加
        $bootgoods_info = array_under_reset($bootgoods_info, 'goods_id');
        if (isset($bootgoods_info[$gid])) {
            $data = array('result' => 'false', 'msg' => lang('goods_already_add'));
            $this->_echoJson($data);
        }

        // 保存到推荐展位商品表
        $insert = array();
        $insert['store_id'] = $this->seller_info['store_id'];
        $insert['goods_id'] = $goods_info['goods_id'];
        $insert['gc_id'] = $goods_info['gc_id'];
        $pbooth_model->addBoothgoods($insert);

        $this->recordSellerlog('添加推荐展位商品，商品id：' . $goods_info['goods_id']);

        // 输出商品信息
        $goods_info['goods_image'] = goods_thumb($goods_info);
        $goods_info['url'] = url('Goods/index', array('goods_id' => $goods_info['goods_id']));
        $goods_class = model('goodsclass')->getGoodsclassInfoById($goods_info['gc_id']);
        $goods_info['gc_name'] = $goods_class['gc_name'];
        $goods_info['result'] = 'true';
        $this->_echoJson($goods_info);
    }

    /**
     * 删除选择商品
     */
    public function del_choosed_goods()
    {
        $gid = input('param.gid');
        if ($gid <= 0) {
            $data = array('result' => 'false', 'msg' => lang('param_error'));
            $this->_echoJson($data);
        }

        $result = model('pbooth')->delBoothgoods(array('goods_id' => $gid, 'store_id' => $this->seller_info['store_id']));
        if ($result) {
            $this->recordSellerlog('删除推荐展位商品，商品id：' . $gid);
            $data = array('result' => 'true');
        }
        else {
            $data = array('result' => 'false', 'msg' => lang('ds_common_del_fail'));
        }
        $this->_echoJson($data);
    }

    /**
     * 输出JSON
     * @param array $data
     */
    private function _echoJson($data)
    {
    	if(isset($data['result']) && $data['result']){
    		unset($data['result']);
    		ds_json_encode(10000,"查询成功",$data);
	    }else{
		    ds_json_encode(10001,$data['msg']);
	    }
        
    }
}